package com.tao.auth.config;

import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.tao.auth.handler.CustomAuthenticationSuccessHandler;
import com.tao.ucenter.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.web.SecurityFilterChain;


/**
 * @author Mr.M
 * @version 1.0
 * @description 安全管理配置
 * @date 2022/9/26 20:53
 */
@EnableWebSecurity
@Configuration
public class WebSecurityConfig {

    @Autowired
    private JWKSource<SecurityContext> jwkSource;  // 添加 JWKSource 注入

    @Autowired
    DaoAuthenticationProviderCustom daoAuthenticationProviderCustom;

    @Autowired
    private CustomAuthenticationSuccessHandler authenticationSuccessHandler;




    @Autowired
    UserServiceImpl userService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        //使用BCrypt加密而不是明文
        return new BCryptPasswordEncoder();
        //return NoOpPasswordEncoder.getInstance();
    }

    //配置安全拦截机制
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/oauth2/**", "/login/** ").permitAll()  // OAuth2端点和登录端点放行
                        .requestMatchers("/r/**").authenticated()  //访问/r开始的请求需要认证通过
                        .anyRequest().permitAll()  //其它请求全部放行
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt.decoder(OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource)))  // 修改这里，使用注入的jwkSource
                )
                .formLogin(form -> form
                        .successHandler(authenticationSuccessHandler)
                )
                .logout(logout -> logout
                        .logoutUrl("/logout")  //退出地址
                )
                .authenticationProvider(daoAuthenticationProviderCustom)
                .csrf(csrf -> csrf.disable()); // 禁用 CSRF 保护

        return http.build();
    }

}